# 初始化文件，创建flask应用

# 导入flask对象
import os

from flask import Flask
from .exts import init_exts, create_socketio_instance
from .views import blue
from .views_pic import blue_pic
from .views_user import blue_user
from .views_search import blue_search
from .views_show import blue_show
from .views_add import blue_add
from .views_chat import blue_chat
from .views_favorite import blue_fav
from datetime import timedelta
from .models import *
from .events import *
from dotenv import load_dotenv


def create_app():
    load_dotenv(verbose=True)
    app = Flask(__name__)
    app.permanent_session_lifetime = timedelta(minutes=20)
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')

    # 创建并配置 SocketIO 实例
    soc = create_socketio_instance(app)

    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS', False)

    # 初始化插件
    init_exts(app)

    # 注册蓝图
    app.register_blueprint(blue)
    app.register_blueprint(blue_pic)
    app.register_blueprint(blue_user)
    app.register_blueprint(blue_search)
    app.register_blueprint(blue_add)
    app.register_blueprint(blue_show)
    app.register_blueprint(blue_chat)
    app.register_blueprint(blue_fav)

    # 定义after_request装饰器，用于添加CORS响应头
    @app.after_request
    def add_cors_headers(response):
        # 生产环境需要配置到具体的域名之下
        # response.headers["Access-Control-Allow-Origin"] = "https://www.example.com"
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
        return response

    return app, soc
